package Broker.yahooJapanAuction;

import com.google.api.translate.Language;
import com.google.api.translate.Translator;
import java.sql.Date;
import java.util.Calendar;
import java.util.ArrayList;
import model.db.table.Bid;
import model.db.table.BidHistory;

/**
 * Author: Raoux Etienne
 * Student login: jc218934
 * Student number: 12448190
 * email: etienne.raoux@my.jcu.edu.au
 * alt email: jc218934@gmail.com
 */
public class UrlExtractorFromList extends Thread
{
    HtmlSourceReaderToList reader;
    private ArrayList<String> itemList;
    private ArrayList<String> itemHistoryList;


    private ArrayList<BidHistory> bidHistoryList;
    private final UrlExtractorListener listener;
    private final String url;
    public UrlExtractorFromList(UrlExtractorListener listener, String url)
    {
        bidHistoryList = new ArrayList<BidHistory>();
        this.listener = listener;
        this.url = url;
        
    }

    public void run()
    {
        try
        {
            reader = new HtmlSourceReaderToList();
            itemList = reader.readProducts(url);
            for (String auctionUrl:itemList)
            {
                String imgUrl = extractImageUrlFromString(auctionUrl);
                String title = extractTitleFromString(auctionUrl);
                String itemUrl = extractItemDescriptionUrlFromString(auctionUrl);
                String sellerUrl = extractSellerUrlFromString(auctionUrl);
                String sellerName = extractSellerFromString(auctionUrl);
                String price = extractPriceFromString(auctionUrl);
                String biddingHistoryUrl = extractItemBiddingHistoryUrlFromString(auctionUrl);

                BidHistory bidHistory = new BidHistory(imgUrl, title, itemUrl, sellerUrl,
                        sellerName, price, downloadAndExtractHistory(biddingHistoryUrl));
                bidHistory.insertInDb();
                bidHistoryList.add(bidHistory);
                listener.addItem(bidHistory);

            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }

    private String extractImageUrlFromString(String str)
    {
        return extractInfo("<img src=\"", "\"", str);
    }

    private String extractTitleFromString(String str)
    {
        str = extractInfo("\" alt=\"", "\"", str);
        Translator translator = new Translator();
        String response = translator.translate(str, Language.JAPANESE, Language.ENGLISH);
        if (response == null) return str;
        return response;
    }

    private String extractItemDescriptionUrlFromString(String str)
    {
        return extractInfo("http://ord.yahoo.co.jp/o/auction/SIG", "\"", str, true, false);
    }

    private String extractSellerUrlFromString(String str)
    {
        str = extractInfoFrom("<div class=\"a4 cf\"><p>" ,str);
        return extractInfo("<a href=\"","\"", str);
    }

    private String extractSellerFromString(String str)
    {
        str = extractInfoFrom("<div class=\"a4 cf\"><p>" ,str);
        return extractInfo("\">","</a>", str);
    }

    private String extractPriceFromString(String str)
    {
        return extractInfo("<td class=\"pr1\">","円", str);
    }

    private String extractItemBiddingHistoryUrlFromString(String str)
    {
        String start = "<td class=\"bi\"><a href=\"";
        if (!str.contains(start))
        {
            return null;
        }
        else
        {
            return extractInfo(start,"\"", str);
        }
    }

    private String extractInfo(String from, String to, String str, boolean fromIncluded, boolean toIncluded)
    {
        str = fromIncluded ? str.substring(str.indexOf(from)) : str.substring(str.indexOf(from)+from.length());
        str = toIncluded ? str.substring(0, str.indexOf(to)+to.length()) : str.substring(0, str.indexOf(to));
        return str;
    }

    private String extractInfo(String from, String to, String str)
    {
        return extractInfo(from, to, str, false, false);
    }

    private String extractInfoFrom (String from, String str, boolean fromIncluded)
    {
        return fromIncluded ? str.substring(str.indexOf(from)) : str.substring(str.indexOf(from)+from.length());
    }

    private String extractInfoFrom (String from, String str)
    {
        return extractInfoFrom (from, str, false);
    }

    private ArrayList<Bid> downloadAndExtractHistory(String url)
    {
        ArrayList<Bid> bidList = new ArrayList <Bid>();
        try
        {
            reader = new HtmlSourceReaderToList();
            itemHistoryList = reader.readHistory(url);
            for (String auctionHistory:itemHistoryList)
            {
                Date date = extractDateOfBid(auctionHistory);
                String bidder = extractBidderOfBid(auctionHistory);
                String bidType = extractBidTypeOfBid(auctionHistory);
                String qty;
                String amt;
                if (bidType.compareTo("automatic") == 0)
                {
                    qty = "1";
                    amt = extractAmtOfBid(auctionHistory);
                }
                else
                {
                    qty = extractQtyOfBid(auctionHistory);
                    amt = extractAmtOfBidWithQty(auctionHistory);
                }

                bidList.add(new Bid(date, bidder, bidType, qty, amt));
            }
        }
        catch (Exception ex)
        {

        }
        return bidList;
    }

    private Date extractDateOfBid(String str)
    {
        String start = "<tr><td class=\"decBg01\">[";
        String tmpStr;
        str = str.substring(str.indexOf(start)+start.length());
        tmpStr = str.substring(0, str.indexOf("��"));
        int month = Integer.parseInt(tmpStr);
        str = str.substring(str.indexOf("��")+"��".length()+1);
        tmpStr = str.substring(0, str.indexOf("��"));
        int day = Integer.parseInt(tmpStr);
        str = str.substring(str.indexOf("��")+"��".length()+1);
        tmpStr = str.substring(0, str.indexOf("��"));
        int hour = Integer.parseInt(tmpStr);
        str = str.substring(str.indexOf("��")+"��".length()+1);
        tmpStr = str.substring(0, str.indexOf("ʬ"));
        int min = Integer.parseInt(tmpStr);
        Calendar cal = Calendar.getInstance();
        cal.set(2011, month -1, day, hour, min);
        Date date = new Date(cal.getTimeInMillis());
        return date;
    }

    private String extractBidderOfBid(String str)
    {
        return extractInfo("] "," ", str);
    }

    private String extractBidTypeOfBid(String str)
    {
        if (str.contains("��ư������")) return "automatic";
        else return "manual";
    }

    private String extractQtyOfBid(String str)
    {
        return extractInfo("���������̡� "," �� ", str);
    }

    private String extractAmtOfBid(String str)
    {
        return extractInfo("��ư������ ","</td>", str);
    }

    private String extractAmtOfBidWithQty(String str)
    {
        return extractInfo(" �� ","</td>", str);
    }
}
